package com.tan.common.tools;

import cn.hutool.core.bean.BeanUtil;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Tan-Bowen
 * @version 1.0
 * @description
 * @date 2021/9/23 15:41
 */
public class StreamTool {

    /**
     * @param [list, fuc]
     * @author Tan-Bowen
     * @description  转换成Map<key,Obj>
     * @date 2021/9/23 15:51
     */
    public static <T, V> Map<V, T> toMap(List<T> list, Function<T, V> fuc) {
        return list.stream().collect(Collectors.toMap(fuc, a -> a, (b, c) -> b));
    }

    public static <T, V, R> Map<V, R> toMap(List<T> list, Function<T, V> key, Function<T, R> value) {
        return list.stream().collect(Collectors.toMap(key, value));
    }

    public static <T, H> Map<H, List<T>> group(List<T> list, Function<T, H> h) {
        return list.stream().collect(Collectors.groupingBy(h));
    }

    public static <T, H> List<H> extract(List<T> list, Function<T, H> h) {
        return list.stream().map(h).collect(Collectors.toList());
    }

    public static <T> List<T> copies(List<?> list, Class<T> cls) {
        return list.stream().map(e -> {
            return BeanUtil.copyProperties(e, cls);
        }).collect(Collectors.toList());
    }
}
